<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use app\admin\model\Storage as StorageModel;

class Storage extends Common
{

    /**
     * 存储列表
     * @author admin
     * @date 2019-08-11
     */
    public function index()
    {
        if (Request::isPost()) {
            $lists = Db::name("Storage")->order("id", "asc")->select();
            return ['code' => 0, 'msg' => '获取成功！', 'data' => $lists];
        }
        return view();
    }


    /**
     * 配置存储参数
     * @author admin
     * @date 2019-08-11
     */
    public function edit()
    {
        try {
            if (Request::isPost()) {
                $data = input("post.");
                $result = StorageModel::setConfig($data['id'], json_encode($data));
                if ($result) {
                    return ['code' => 0, 'msg' => '操作成功!'];
                }
                return ['code' => 2000, 'msg' => '操作失败!'];
            } else {
                $id = input("request.id", 0, "intval");
                if (!$id) return ['code' => 2000, 'msg' => '非法请求!'];
                $info = Db::name("storage")->where("id", $id)->find();
                $this->assign('id', $id);
                $this->assign('info', $info['value']);
                return View::fetch($info['alias']);
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 更改存储状态
     * @param $id 主键
     * @param $status 值
     * @return Array
     */
    public function doStatus()
    {
        try {
            $id = input('request.id');
            $status = input('request.status');
            if (!$id) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $result = Db::name("storage")->where("id", "<>", $id)->update(['status' => 0]);
            $result = Db::name("storage")->where("id", $id)->update(['status' => $status]);
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }

    }

}
